package com.hrma.controller;

import com.hrma.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.PostConstruct;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.*;

/**
 * create by 2023/2/20.
 *
 * @author udbjqr
 */
@RestController
@Slf4j
public class FileUpload {
	@Value("${server.servlet.context-path}${mvc.image.url}")
	private String url;
	@Value("${mvc.image.path}")
	private String basePath;
	Set<PosixFilePermission> set = new TreeSet<>();

	@PostConstruct
	public void init(){
		set.add(PosixFilePermission.GROUP_WRITE);
		set.add(PosixFilePermission.OWNER_WRITE);
		set.add(PosixFilePermission.OWNER_READ);
		set.add(PosixFilePermission.GROUP_READ);
		set.add(PosixFilePermission.OTHERS_READ);
		set.add(PosixFilePermission.OTHERS_WRITE);
	}


	@RequestMapping("/upload-file")
	public Result<List<String>> upload(MultipartHttpServletRequest request) {
		List<String> ss = new ArrayList<>();
		//创建存放目录
		Calendar c = Calendar.getInstance();
		String path = String.format("%d%02d%02d", c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH));
		File dir = new File(basePath + path);
		if (!dir.exists()) {
			if (!dir.mkdir()){
				throw new RuntimeException("创建目录失败:" + dir.getName());
			}
		}
		//可能有多个文件上传，循环处理
		request.getMultiFileMap().forEach((name, f) -> {
			//因为传入的每个部分是一个list,所以需要使用get(0)得到文件对象。
			MultipartFile file = f.get(0);
			if (file == null || file.getSize() <= 0) return;

			//生成新的文件名
			UUID uuid = UUID.randomUUID();
			//从源文件名获得扩展名。
			String upFileName = file.getOriginalFilename();
			assert upFileName != null;
			String fileName = uuid.toString().trim().replace("-", "") + upFileName.substring(upFileName.lastIndexOf('.'));

			//根据指定的目录存放
			File saveFile = new File(dir + "/" + fileName);

			//写入内容
			try (
				InputStream inputStream = file.getInputStream();
				OutputStream outputStream = new FileOutputStream(saveFile)
			) {
				int byteRead;
				byte[] buffer = new byte[8192];
				while ((byteRead = inputStream.read(buffer, 0, 8192)) != -1) {
					outputStream.write(buffer, 0, byteRead);
				}

				//设置文件的权限
				Files.setPosixFilePermissions(saveFile.toPath(),set);
				ss.add(url + path + "/" + fileName);
			} catch (IOException e) {
				log.error("出现异常。", e);
				throw new RuntimeException(e);
			}
		});

		return Result.ok(ss);
	}
}
